package com.ssh.service;

import java.util.List;

import javax.inject.Inject;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;

import com.ssh.dao.IUserDao;
import com.ssh.exception.UserException;
import com.ssh.model.Pager;
import com.ssh.model.User;

@Service("userService")
public class UserService implements IUserService {
	
	private IUserDao userDao;
	
	public IUserDao getUserDao() {
		return userDao;
	}

	@Inject
	public void setUserDao(IUserDao userDao) {
		this.userDao = userDao;
	}

	@Override
	public void addUser(User user) {
		User u = userDao.getUser(user.getName());
		if(u!=null){
			throw new UserException(user.getName() + " is already existed.");
		}else{
			userDao.addUser(user);
			Logger.getLogger("service").debug("service:adding a user...");
		}
	}

	@Override
	public void updateUser(User user) {
		User u = userDao.getUser(user.getId(), user.getName());
		if(u!=null){
			throw new UserException(user.getName() + " is already existed.");
		}else{
			userDao.updateUser(user);
			Logger.getLogger("service").debug("service:updating a user...");
		}
	}

	@Override
	public void deleteUser(int id) {
		userDao.deleteUser(id);
		Logger.getLogger("service").debug("service:deleting a user...");
	}

	@Override
	public List<User> getUsers() {
		Logger.getLogger("service").debug("service:getting users...");
		return userDao.getUsers();
	}

	@Override
	public User getUser(int id) {
		Logger.getLogger("service").debug("service:getting a user by id...");
		return userDao.getUser(id);
	}
	

	@Override
	public Pager<User> findUsers() {
		Logger.getLogger("service").debug("service:getting pagers...");
		return userDao.findUsers();
	}
	
	@Override
	public User login(String name, String password) {
		User u = userDao.getUser(name);
		if(u==null) {
			throw new UserException("no user's name like : "+name);
		}else if(!u.getPassword().equals(password)){
			throw new UserException("password is not correct");
		}
		Logger.getLogger("service").debug("service:logining...");
		return u;
	}
}
